import {
  _decorator,
  Animation,
  Collider2D,
  Component,
  Contact2DType,
  IPhysics2DContact,
  Sprite,
} from "cc";
import { UIBullet } from "./UIBullet";
import { GameManager } from "../GameManager";
const { ccclass, property } = _decorator;

@ccclass("UIEnemy")
export class UIEnemy extends Component {
  @property
  speed: number = 300;

  @property(Animation)
  anim: Animation = null!;

  @property
  animHit: string = "";
  @property
  animDown: string = "";
  @property
  score: number = 100;

  @property
  hp: number = 1;

  collder: Collider2D = null;
  start() {
    this.collder = this.node.getComponent(Collider2D);
    if (this.collder) {
      this.collder.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }
  }
  protected onDestroy(): void {
    if (this.collder) {
      this.collder.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }
  }

  update(deltaTime: number) {
    if (this.hp > 0) {
      const pos = this.node.getPosition();
      this.node.setPosition(pos.x, pos.y - this.speed * deltaTime, pos.z);
    }

    if (this.node.position.y < -580) {
      this.node.destroy();
    }
  }

  onBeginContact(
    selfCollider: Collider2D,
    otherCollider: Collider2D,
    contact: IPhysics2DContact | null
  ) {
    // console.log(this.node.name);
    // 禁用子弹的碰撞器和精灵
    if (otherCollider.getComponent(UIBullet)) {
      otherCollider.enabled = false;
      otherCollider.getComponent(Sprite).enabled = false;
    }
    this.hp -= 1;

    // 除了enemy0 被击中都播放hit动画
    if (selfCollider.node.name != "enemy0") {
      this.anim.play(this.animHit);
    }

    if (this.hp <= 0) {
      GameManager.getInstance().addScore(this.score);
      // 播放down动画
      if (selfCollider.node.name != "enemy0") {
        this.anim.play(this.animDown);
      } else {
        this.anim.play();
      }

      if (this.collder) {
        this.collder.enabled = false;
      }
      this.scheduleOnce(() => {
        this.node.destroy();
      }, 1);
    }
  }
}
